package com.mtnz.njk.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.Util.*;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.MyOrderModel;
import com.mtnz.njk.model.UserCouponModel;
import com.mtnz.njk.model.UserIndexPageModel;
import com.mtnz.njk.model.UserInfoModel;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: 范保林
 * @Date: 2019\6\14 0014 15:15
 * @Description: 用户基本操作
 */
@Service
public class NjkUserService {
    @Autowired
    NjkUserMapper njkUserMapper;

    @Autowired
    AuthCodeMapper authCodeMapper;

    @Autowired
    NjkUserInfoMapper njkUserInfoMapper;

    @Autowired
    NjkUserAddressMapper addressMapper;

    @Autowired
    OpinionMapper opinionMapper;

    @Autowired
    OpinionImgMapper opinionImgMapper;

    @Autowired
    UserSignMapper userSignMapper;

    @Autowired
    UserTaskMapper userTaskMapper;

    @Autowired
    CountCommunityMapper countCommunityMapper;

    @Autowired
    UserSignCountMapper userSignCountMapper;

    @Autowired
    UserTaskCountMapper userTaskCountMapper;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderProductMapper orderProductMapper;

    @Autowired
    ProductRemarkMapper productRemarkMapper;

    @Autowired
    NjkUserServiceMapper njkUserServiceMapper;

    @Autowired
    NjkUserAddressMapper userAddressMapper;

    @Autowired
    BalanceOrderMapper balanceOrderMapper;

    @Autowired
    InquiryMapper inquiryMapper;


    /**
     * 检验用户是否存在
     *
     * @param phone
     * @return
     */
    // @Cacheable(value = "userCache",key = "#phone",unless = "#result == null ")
    public NjkUserEntity checkUser(String phone) {
        // 查询该用户
        NjkUserEntity njk = new NjkUserEntity();
        njk.setPhone(phone);
        NjkUserEntity user = njkUserMapper.selectOne(njk);
        return user;
    }

    /**
     * 更新用户的登录时间和机型
     *
     * @param user
     */
    @Transactional
    public void updateLastLogin(NjkUserEntity user) throws Exception {
        // 更新用户的登录时间
        njkUserMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 农极客用户手机发送验证码
     *
     * @param phone
     * @param request
     * @return
     */
    @Transactional
    public ResponseResult saveAuthCode(String phone, HttpServletRequest request) throws Exception {
        // 生成验证码
        String authCode = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        System.out.println("验证码为：" + authCode);
        // 阿里云发送验证码
        Map<String, Object> data = new HashMap<>();
        data.put("code", authCode);
        AaliSMS.sendSms(phone, AaliSMS.authCode, AaliSMS.josnofObject(data));
        String ip = "";
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        } else {
            ip = request.getHeader("x-forwarded-for");
        }
        String uuid = UuidUtil.get32UUID();
        AuthCodeEntity code = new AuthCodeEntity();
        code.setAuthCodeId(uuid);
        code.setAuthCode(authCode);
        code.setCreateTime(DateUtil.getTime());
        // 得到验证码的到期时间
        Calendar nowTime = Calendar.getInstance();
        Date nowDate = (Date) nowTime.getTime(); // 得到当前时间
        Calendar afterTime = Calendar.getInstance();
        afterTime.add(Calendar.MINUTE, 5); // 当前分钟+5
        Date afterDate = (Date) afterTime.getTime();
        String deadTime = cn.hutool.core.date.DateUtil.format(afterDate, "yyyy-MM-dd HH:mm:ss");
        code.setDeadTime(deadTime);
        code.setPhone(phone);
        code.setIp(ip);
        // 保存用户发送的验证码
        int insert = authCodeMapper.insert(code);
        if (insert > 0)
            return new ResponseResult(ResponseMessage.OK, authCode);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 检验验证码是否正确
     *
     * @param authCode
     * @return
     */
    public HashMap<String, Object> checkAuthCode(String phone, String authCode) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        // 取出用户最近请求的验证码
        AuthCodeEntity code = authCodeMapper.checkAuthCode(phone);
        // 检查该验证码是否存在
        if (code == null) {
            result.put("fail", "验证码不存在");
            return result;
        }
        if (!(code.getAuthCode().equals(authCode))) {
            result.put("fail", "该验证码输入错误");
            return result;
        }
        // 检查验证码是否过期
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long time = sdfTime.parse(DateUtil.getTime()).getTime();
        long deadTime = sdfTime.parse(code.getDeadTime()).getTime();
        // 验证码过期
        if (time > deadTime) {
            result.put("fail", "验证码过期");
            return result;
        }
        result.put("ok", "验证成功");
        return result;
    }

    /**
     * 用户注册信息
     *
     * @param nickName
     * @param password
     * @param phone
     * @param job
     * @return
     */
    @Transactional
    public ResponseResult register(String nickName, String password, String phone, String job, String headimgurl, String unionid, String openid) throws Exception {
        // 检查该手机号是否注册
        Example example2 = new Example(NjkUserEntity.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("phone", phone);
        NjkUserEntity user = njkUserMapper.selectOneByExample(example2);
        if (user != null) {
            return new ResponseResult(ResponseMessage.FAIL, "该用户已注册");
        } else {
            // 检查昵称是否被使用
            Example example = new Example(NjkUserEntity.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("nickName", nickName);
            List<NjkUserEntity> select = njkUserMapper.selectByExample(example);
            if (select != null && select.size() > 0) {
                // 昵称不可用
                return new ResponseResult(ResponseMessage.FAIL, "该昵称不可用");
            }
            // 使用uuid生成用户主键
            String uuid = UuidUtil.get32UUID();
            // 生成盐
            String salt = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
            // 对用户密码加密
            String pwd = MD5.md5(MD5.md5(password) + salt);

            NjkUserEntity njkUser = new NjkUserEntity();
            njkUser.setUserId(uuid);
            njkUser.setCreateTime(DateUtil.getTime());
            njkUser.setLastLogin(DateUtil.getTime());
            njkUser.setSalt(salt);
            njkUser.setPassword(pwd);
            njkUser.setPhone(phone);
            njkUser.setNickName(nickName);
            njkUser.setUnionId(unionid);
            njkUser.setOpenId(openid);

            // 添加客户基本信息
            int i1 = njkUserMapper.insertSelective(njkUser);
            // 添加客户扩展信息
            NjkUserInfoEntity njkUserInfo = new NjkUserInfoEntity();
            njkUserInfo.setUserId(njkUser.getUserId());
            njkUserInfo.setJob(job);
            // 给注册用户添加默认头像
            njkUserInfo.setImg("http://www.meitiannongzi.com/NJK/img/156689241.png");
            int i = njkUserInfoMapper.insertSelective(njkUserInfo);
            if (i > 0 && i1 > 0)
                return new ResponseResult(ResponseMessage.OK);
            return new ResponseResult(ResponseMessage.FAIL);
        }
    }

    /**
     * 使用微信登录
     *
     * @param unionId
     * @param phoneType
     * @return
     */
    @Transactional
    public ResponseResult wxLogin(String unionId, String phoneType) throws Exception {
        NjkUserEntity user = new NjkUserEntity();
        user.setUnionId(unionId);
        // 查询该用户是否用微信登录过
        NjkUserEntity njkUser = njkUserMapper.selectOne(user);
        if (njkUser == null) {
            return new ResponseResult(ResponseMessage.FAIL, "该微信未关联账号");
        }

        //修改用户登录机型
        if (phoneType != null && !(phoneType.equals(""))) {
            Example example = new Example(NjkUserEntity.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("unionId", unionId);
            user.setPhoneType(phoneType);
            njkUserMapper.updateByExampleSelective(user, example);
        }
        return new ResponseResult(ResponseMessage.OK, njkUser);
    }


    /**
     * 微信关联账号登录
     *
     * @param phone
     * @param authCode
     * @return
     */
    public ResponseResult wxRelevanceAccount(String phone, String authCode, String headimgurl, String unionid, String openid, String nickname) throws Exception {
        // 判断该手机号是否存在
        Example example = new Example(NjkUserEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("phone", phone);
        NjkUserEntity njkUserEntity = njkUserMapper.selectOneByExample(example);
        if (njkUserEntity == null) {
            return new ResponseResult(ResponseMessage.FAIL, "该手机号不存在");
        }
        // 检查验证码是否正确
        if (authCode != null && !(authCode.equals(""))) {
            HashMap<String, Object> result = checkAuthCode(phone, authCode);
            // 验证码正确
            if (result.containsKey("ok")) {
                // 将微信信息插入用户信息中
                if (njkUserEntity.getNickName() == null) {
                    njkUserEntity.setNickName(nickname);
                }
                njkUserEntity.setUnionId(unionid);
                njkUserEntity.setOpenId(openid);
                // 查询用户扩展信息
                Example njkUserInfoExample = new Example(NjkUserInfoEntity.class);
                njkUserInfoExample.createCriteria().andEqualTo("userId", njkUserEntity.getUserId());
                NjkUserInfoEntity njkUserInfoEntity = njkUserInfoMapper.selectOneByExample(njkUserInfoExample);
                if (njkUserInfoEntity.getImg() != null && !("").equals(njkUserInfoEntity.getImg())) {
                    njkUserInfoEntity.setImg(headimgurl);
                    // 修改用户头像
                    njkUserInfoMapper.updateByPrimaryKeySelective(njkUserInfoEntity);
                }
                njkUserMapper.updateByPrimaryKeySelective(njkUserEntity);
                return new ResponseResult(ResponseMessage.OK, njkUserEntity);
            }
            return new ResponseResult(ResponseMessage.FAIL, result.get("fail"));
        }
        return new ResponseResult(ResponseMessage.FAIL, "验证码不存在");
    }

    /**
     * 判断手机号是否注册
     *
     * @param phone
     * @return
     * @throws Exception
     */
    public ResponseResult phoneIfRegister(String phone) throws Exception {
        Example userExample = new Example(NjkUserEntity.class);
        userExample.createCriteria().andEqualTo("phone", phone);
        NjkUserEntity userEntity = njkUserMapper.selectOneByExample(userExample);
        if (userEntity == null) {
            return new ResponseResult(ResponseMessage.OK);
        }
        return new ResponseResult(ResponseMessage.FAIL, "该手机号已注册");
    }

    /**
     * 忘记密码
     *
     * @param phone
     * @param password
     * @param authCode
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult forgetPassword(String phone, String password, String authCode) throws Exception {
        // 检查该手机号是否存在于用户中
        Example example = new Example(NjkUserEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("phone", phone);
        NjkUserEntity njkUser = njkUserMapper.selectOneByExample(example);
        if (njkUser == null) {
            return new ResponseResult(ResponseMessage.FAIL, "该用户不存在");
        }
        // 验证码是否正确
        HashMap<String, Object> result = checkAuthCode(phone, authCode);
        if (result.containsKey("fail")) {
            return new ResponseResult(ResponseMessage.FAIL, result.get("fail"));
        }
        // 对密码加密
        String md5Password = MD5.md5(MD5.md5(password) + njkUser.getSalt());
        // 重置密码
        njkUser.setPassword(md5Password);
        njkUserMapper.updateByPrimaryKeySelective(njkUser);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 重置密码
     *
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Transactional
    public ResponseResult resetPassword(String userId, String oldPassword, String newPassword) throws Exception {
        // 查询该用户的信息
        NjkUserEntity njkUserEntity = njkUserMapper.selectByPrimaryKey(userId);
        if (njkUserEntity != null) {
            // 得到加密盐
            String salt = njkUserEntity.getSalt();
            // 对旧密码加密
            String oldMd5Password = MD5.md5(MD5.md5(oldPassword) + salt);
            // 检查旧密码是否正确
            if (!(oldMd5Password.equals(njkUserEntity.getPassword()))) {
                return new ResponseResult(ResponseMessage.FAIL, "原密码输入不正确");
            }
            // 对新密码进行加密
            String newMd5Password = MD5.md5(MD5.md5(newPassword) + salt);
            NjkUserEntity njkUserEntity1 = new NjkUserEntity();
            njkUserEntity.setUserId(userId);
            njkUserEntity1.setPassword(newMd5Password);
            // 重置密码
            int result = njkUserMapper.updateByPrimaryKeySelective(njkUserEntity);
            if (result > 0)
                return new ResponseResult(ResponseMessage.OK);
            return new ResponseResult(ResponseMessage.UPDATE_FAIL);
        }
        return new ResponseResult(ResponseMessage.FAIL, "用户不存在");
    }

    /**
     * 用户个人信息
     *
     * @param userId
     * @return
     */
    public ResponseResult userInfoMessage(String userId) throws Exception {
        // 查询用户个人基本信息
        NjkUserEntity njkUserEntity = njkUserMapper.selectByPrimaryKey(userId);
        // 查询用户扩展信息
        Example example = new Example(NjkUserInfoEntity.class);
        example.createCriteria().andEqualTo("userId", userId);
        NjkUserInfoEntity njkUserInfoEntity = njkUserInfoMapper.selectOneByExample(example);
        // 用户个人信息模型
        UserInfoModel userInfoModel = new UserInfoModel();
        // 实体类转模型
        userInfoModel.setUserId(userId);
        userInfoModel.setImg(njkUserInfoEntity.getImg());
        userInfoModel.setNickName(njkUserEntity.getNickName());
        userInfoModel.setSex(Integer.valueOf(njkUserInfoEntity.getSex()));
        userInfoModel.setWxNumber(njkUserInfoEntity.getWxNumber());
        userInfoModel.setPhone(njkUserEntity.getPhone());
        userInfoModel.setJob(njkUserInfoEntity.getJob());
        userInfoModel.setAddress(njkUserInfoEntity.getAddress());
        userInfoModel.setSign(njkUserInfoEntity.getSign());
        userInfoModel.setBalance(njkUserEntity.getBalance());
        userInfoModel.setVip(njkUserEntity.getVip());
        return new ResponseResult(ResponseMessage.OK, userInfoModel);
    }

    /**
     * 用户修改个人信息
     *
     * @param userInfoModel
     * @return
     */
    @Transactional
    public ResponseResult updateUserInfoMessage(UserInfoModel userInfoModel) throws Exception {
        boolean update = false;
        // 修改个人基本信息
        NjkUserEntity njkUserEntity = new NjkUserEntity();
        njkUserEntity.setUserId(userInfoModel.getUserId());
        if (userInfoModel.getImg() != null && userInfoModel.getImg() != "") {
            njkUserEntity.setImg(userInfoModel.getImg());
            update = true;
        }
        if (userInfoModel.getNickName() != null && userInfoModel.getNickName() != "") {
            njkUserEntity.setNickName(userInfoModel.getNickName());
            update = true;
        }
        if (userInfoModel.getPhone() != null && userInfoModel.getPhone() != "") {
            njkUserEntity.setPhone(userInfoModel.getPhone());
            update = true;
        }

        if (update == true) {
            njkUserMapper.updateByPrimaryKeySelective(njkUserEntity);
        }
        boolean updateUserInfo = false;
        // 修改个人扩展信息
        NjkUserInfoEntity njkUserInfoEntity = new NjkUserInfoEntity();
        njkUserInfoEntity.setUserId(userInfoModel.getUserId());

        if (userInfoModel.getImg() != null && userInfoModel.getImg() != "") {
            njkUserInfoEntity.setImg(userInfoModel.getImg());
            updateUserInfo = true;
        }
        if (userInfoModel.getSex() != null) {
            njkUserInfoEntity.setSex(userInfoModel.getSex().toString());
            updateUserInfo = true;
        }
        if (userInfoModel.getWxNumber() != null && userInfoModel.getWxNumber() != "") {
            njkUserInfoEntity.setWxNumber(userInfoModel.getWxNumber());
            updateUserInfo = true;
        }
        if (userInfoModel.getJob() != null && userInfoModel.getJob() != "") {
            njkUserInfoEntity.setJob(userInfoModel.getJob());
            updateUserInfo = true;
        }
        if (userInfoModel.getAddress() != null && userInfoModel.getAddress() != "") {
            njkUserInfoEntity.setAddress(userInfoModel.getAddress());
            updateUserInfo = true;
        }
        if (userInfoModel.getSign() != null && userInfoModel.getSign() != "") {
            njkUserInfoEntity.setSign(userInfoModel.getSign());
            updateUserInfo = true;
        }

        if(userInfoModel.getProvince() != null && userInfoModel.getCity() != null && userInfoModel.getDistrict() != null){
            njkUserInfoEntity.setProvince(userInfoModel.getProvince());
            njkUserInfoEntity.setCity(userInfoModel.getCity());
            njkUserInfoEntity.setDistrict(userInfoModel.getDistrict());
            updateUserInfo = true;
        }
        if (updateUserInfo == true) {
            Example example = new Example(NjkUserInfoEntity.class);
            example.createCriteria().andEqualTo("userId", userInfoModel.getUserId());
            njkUserInfoMapper.updateByExampleSelective(njkUserInfoEntity, example);
        }

        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 用户添加收货地址
     *
     * @param addressEntity
     * @return
     */
    public ResponseResult addUserAddress(NjkUserAddressEntity addressEntity) {
        // 用户没有勾选为默认地址 直接新增
        if (addressEntity.getDefaultAddress() == 0) {
            String uuid = IdUtil.simpleUUID();
            addressEntity.setAddressId(uuid);
            addressEntity.setDefaultAddress(0);
            int i = addressMapper.insertSelective(addressEntity);
            if (i > 0)
                return new ResponseResult(ResponseMessage.OK);
            return new ResponseResult(ResponseMessage.FAIL);
        }
        if (addressEntity.getDefaultAddress() == 1) {
            // 用户勾选默认地址，其他默认地址设为0
            Example example = new Example(NjkUserAddressEntity.class);
            example.createCriteria().andEqualTo("userId", addressEntity.getUserId());
            NjkUserAddressEntity njkUserAddressEntity = new NjkUserAddressEntity();
            njkUserAddressEntity.setDefaultAddress(0);
            addressMapper.updateByExampleSelective(njkUserAddressEntity, example);
            // 传入地址设为1并插入

            String uuid = IdUtil.simpleUUID();
            addressEntity.setAddressId(uuid);
            addressEntity.setDefaultAddress(1);
            addressEntity.setAddressId(uuid);
            int i = addressMapper.insertSelective(addressEntity);
            if (i > 0)
                return new ResponseResult(ResponseMessage.OK);
            return new ResponseResult(ResponseMessage.FAIL);
        }
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 用户收货地址列表
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public ResponseResult listUserAddress(Integer pageNum, Integer pageSize, String userId) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 查询用户的收货地址
        List<NjkUserAddressEntity> njkUserAddressEntities = njkUserMapper.listUserAddress(userId);
        PageInfo<NjkUserAddressEntity> njkUserAddressEntityPageInfo = new PageInfo<>(njkUserAddressEntities);
        return new ResponseResult(ResponseMessage.OK, njkUserAddressEntityPageInfo);
    }

    /**
     * 用户修改收货地址
     *
     * @param addressEntity
     * @return
     * @throws Exception
     */
    public ResponseResult updateUserAddress(NjkUserAddressEntity addressEntity) throws Exception {
        // 没有设为默认地址
        if (addressEntity.getDefaultAddress() == 0) {
            int i = addressMapper.updateByPrimaryKeySelective(addressEntity);
            if (i > 0)
                return new ResponseResult(ResponseMessage.OK);
            return new ResponseResult(ResponseMessage.UPDATE_FAIL);
        }
        // 修改为默认地址
        if (addressEntity.getDefaultAddress() == 1) {
            // 用户其他地址设为非默认
            njkUserMapper.updateOtherAddress(addressEntity);
            // 将这个地址设置为默认并修改
            int i = addressMapper.updateByPrimaryKeySelective(addressEntity);
            if (i > 0)
                return new ResponseResult(ResponseMessage.OK);
            return new ResponseResult(ResponseMessage.UPDATE_FAIL);
        }
        return new ResponseResult(ResponseMessage.UPDATE_FAIL);
    }

    /**
     * 用户删除收货地址
     *
     * @param addressId
     * @return
     * @throws Exception
     */
    public ResponseResult delUserAddress(String addressId) throws Exception {
        int i = addressMapper.deleteByPrimaryKey(addressId);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK);
        return new ResponseResult(ResponseMessage.UPDATE_FAIL);
    }

    /**
     * 用户咨询客服
     *
     * @param userId
     * @param productId
     * @return
     * @throws Exception
     */
    public ResponseResult consultService(String userId, String productId) throws Exception {
        // 查询商品名字和客服手机号
        HashMap<String, String> map = njkUserMapper.selectProductName(productId);
        String productName = map.get("name").toString();
        String phone = map.get("phone").toString();

        // 查询用户名字
        String userName = njkUserMapper.selectUserName(userId);
        String context = "用户(" + userName + ")对" + productName
                + "有意向,请尽快和用户联系.";
        SmsBao sms = new SmsBao();
        sms.sendSMS(phone, context);

        // 新增一条咨询信息
        InquiryEntity inquiryEntity = new InquiryEntity();
        inquiryEntity.setUserId(userId);
        inquiryEntity.setNickName(userName);
        inquiryEntity.setCreateTime(new Date());
        inquiryEntity.setProductName(productName);
        inquiryEntity.setProductId(productId);
        inquiryEntity.setInquiryStatus(0);
        inquiryMapper.insert(inquiryEntity);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 我的代金券
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public ResponseResult myCoupon(String userId, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 查询用户所有代金券(移除过期后变为可用优惠券)
        List<CouponEntity> canUseCoupon = njkUserMapper.queryAllCoupon(userId);
        PageInfo<CouponEntity> couponEntityPageInfo = new PageInfo<>(canUseCoupon);
        List<CouponEntity> list = couponEntityPageInfo.getList();
        // 过期优惠券
        List<CouponEntity> pastCoupon = new ArrayList<>();
        Iterator<CouponEntity> iterator = list.iterator();
        while (iterator.hasNext()) {
            // 已失效代金券
            CouponEntity coupon = iterator.next();
            if (new Date().after(coupon.getEndTime())) {
                pastCoupon.add(coupon);
                iterator.remove();
            }
        }
        UserCouponModel userCouponModel = new UserCouponModel();
        userCouponModel.setCanUseCoupon(canUseCoupon);
        userCouponModel.setPastCoupon(pastCoupon);
        userCouponModel.setPages(couponEntityPageInfo.getPages());
        return new ResponseResult(ResponseMessage.OK, userCouponModel);
    }

    /**
     * 用户反馈建议
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult userOpinion(String userId, String message, String imgs) throws Exception {
        // 查询用户信息
        NjkUserEntity userEntity = njkUserMapper.selectByPrimaryKey(userId);
        if (userEntity == null) {
            return new ResponseResult(ResponseMessage.FAIL, "该用户不存在");
        }
        List<String> opinionImgs = new ArrayList<>();
        if (imgs != null && !imgs.equals("")) {
            String[] split = imgs.split(",");
            opinionImgs = Arrays.asList(split);
        }
        String opinionId = IdUtil.simpleUUID();
        OpinionEntity opinionEntity = new OpinionEntity();
        opinionEntity.setOpinionId(opinionId);
        opinionEntity.setMessage(message);
        opinionEntity.setCreateTime(new Date());
        opinionEntity.setPhone(userEntity.getPhone());
        opinionEntity.setUserId(userId);
        opinionEntity.setStatus(0);
        // 新增反馈信息
        opinionMapper.insertSelective(opinionEntity);
        // 新增反馈图片
        OpinionImgEntity opinionImgEntity = new OpinionImgEntity();

        for (String opinionImg : opinionImgs) {
            opinionImgEntity.setOpinionId(opinionId);
            opinionImgEntity.setImg(opinionImg);
            opinionImgMapper.insertSelective(opinionImgEntity);
        }
        return new ResponseResult(ResponseMessage.OK);

    }

    /**
     * 我的信息首页
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult userIndexPage(String userId) throws Exception {
        UserIndexPageModel userIndexPageModel = new UserIndexPageModel();
        // 查询用户信息
        NjkUserEntity userEntity = njkUserMapper.selectByPrimaryKey(userId);
        if (userEntity == null) {
            return new ResponseResult(ResponseMessage.FAIL, "用户不存在");
        }
        Integer integral = userEntity.getIntegral();
        // 查询用户签到信息
        UserSignEntity userSign = njkUserMapper.getUserSign(userId);
        if (userSign == null) {
            UserSignEntity userSignEntity = new UserSignEntity();
            userSignEntity.setDaysNum(0);
            userSignEntity.setToday(0);
            userSignEntity.setSignDate(cn.hutool.core.date.DateUtil.now());
            userSignEntity.setUserId(userId);
            userSignEntity.setDaysStatus(0);
            userSignEntity.setCreateTime(new Date());
            userSignEntity.setUpdateTime(new Date());
            userSign = userSignEntity;
            // 保存用户签到信息
            userSignMapper.insertSelective(userSignEntity);

        }
        // 查询用户任务信息
        UserTaskEntity userTask = njkUserMapper.getUserTask(userId);
        if (userTask == null) {
            UserTaskEntity userTaskEntity = new UserTaskEntity();
            userTaskEntity.setUserId(userId);
            userTaskEntity.setDailyStatus(0);
            userTaskEntity.setIntegralStatus(0);
            userTaskEntity.setQuizStatus(0);
            userTaskEntity.setResearchStatus(0);
            userTaskEntity.setShareStatus(0);
            userTaskEntity.setCreateTime(new Date());
            userTaskEntity.setUpdateTime(new Date());
            userTaskEntity.setQuizNum(0);
            userTaskEntity.setResearchNum(0);
            userTaskEntity.setShareNum(0);
            userTask = userTaskEntity;
            // 保存用户任务信息
            userTaskMapper.insertSelective(userTaskEntity);
        }
        userIndexPageModel.setIntegral(integral);
        userIndexPageModel.setDaysNum(userSign.getDaysNum());
        userIndexPageModel.setToday(userSign.getToday());
        userIndexPageModel.setDailyStatus(userTask.getDailyStatus());
        userIndexPageModel.setIntegralStatus(userTask.getIntegralStatus());
        userIndexPageModel.setQuizStatus(userTask.getQuizStatus());
        userIndexPageModel.setResearchStatus(userTask.getResearchStatus());
        userIndexPageModel.setShareStatus(userTask.getShareStatus());
        userIndexPageModel.setTotalIntegral(userEntity.getTotalIntegral());
        return new ResponseResult(ResponseMessage.OK, userIndexPageModel);
    }

    /**
     * 用户签到
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult userSign(String userId, Integer integral) throws Exception {
        // 修改用户每日签到信息(没有就新增)
        Example userSignExample = new Example(UserSignEntity.class);
        userSignExample.createCriteria().andEqualTo("userId", userId);
        UserSignEntity userSign = userSignMapper.selectOneByExample(userSignExample);
        if (userSign != null) {
            userSign.setDaysNum(userSign.getDaysNum() + 1);
            userSign.setToday(1);
            userSign.setSignDate(cn.hutool.core.date.DateUtil.now());
            userSign.setUpdateTime(new Date());
            userSignMapper.updateByExample(userSign, userSignExample);
        } else {
            UserSignEntity userSignEntity = new UserSignEntity();
            userSignEntity.setUserId(userId);
            userSignEntity.setDaysNum(1);
            userSignEntity.setToday(1);
            userSignEntity.setDaysStatus(0);
            userSignEntity.setSignDate(cn.hutool.core.date.DateUtil.now());
            userSignEntity.setUpdateTime(new Date());
            userSignEntity.setCreateTime(new Date());
            userSignMapper.insertSelective(userSignEntity);
        }
        // 查询用户信息
        NjkUserEntity userEntity = njkUserMapper.selectByPrimaryKey(userId);
        // 增加用户积分，总积分
        userEntity.setUserId(userId);
        userEntity.setIntegral(userEntity.getIntegral() + integral);
        userEntity.setTotalIntegral(userEntity.getTotalIntegral() + integral);
        njkUserMapper.updateByPrimaryKeySelective(userEntity);

        // 增加一条积分增加记录
        CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
        countCommunityEntity.setCommunityType(9);
        countCommunityEntity.setCreateTime(new Date());
        countCommunityEntity.setUserId(userId);
        countCommunityEntity.setNum(integral + "");
        countCommunityEntity.setNews("参与每日签到");
        countCommunityMapper.insertSelective(countCommunityEntity);

        // 修改用户任务，签到任务状态（没有就新增）
        Example userTaskExample = new Example(UserTaskEntity.class);
        userTaskExample.createCriteria().andEqualTo("userId", userId);
        UserTaskEntity userTask = userTaskMapper.selectOneByExample(userTaskExample);
        if (userTask != null) {
            userTask.setDailyStatus(1);
            userTaskMapper.updateByExampleSelective(userTask, userTaskExample);
        } else {
            UserTaskEntity userTaskEntity = new UserTaskEntity();
            userTaskEntity.setUserId(userId);
            userTaskEntity.setDailyStatus(1);
            userTaskEntity.setIntegralStatus(0);
            userTaskEntity.setQuizStatus(0);
            userTaskEntity.setResearchStatus(0);
            userTaskEntity.setShareStatus(0);
            userTaskEntity.setCreateTime(new Date());
            userTaskEntity.setUpdateTime(new Date());
            userTaskEntity.setQuizNum(0);
            userTaskEntity.setResearchNum(0);
            userTaskEntity.setShareNum(0);
            userTaskMapper.insertSelective(userTaskEntity);
        }

        // 添加一条签到信息
        UserSignCountEntity userSignCountEntity = new UserSignCountEntity();
        userSignCountEntity.setUserId(userId);
        userSignCountEntity.setCreateTime(new Date());
        userSignCountMapper.insertSelective(userSignCountEntity);

        // 添加一条任务信息
        UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
        userTaskCountEntity.setUserId(userId);
        userTaskCountEntity.setTaskType(1);
        userTaskCountEntity.setCreateTime(new Date());
        userTaskCountMapper.insertSelective(userTaskCountEntity);

        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 我的订单
     *
     * @param userId
     * @param orderProductId
     * @return
     * @throws Exception
     */
    public ResponseResult myOrder(String orderNumber, String userId, String orderProductId, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        if (orderProductId != null && !("").equals(orderProductId)) {
            // 查询订单商品详细id
        }

        if (orderNumber != null && !("").equals(orderNumber)) {
            Example orderInfoExample = new Example(OrderInfoEntity.class);
            orderInfoExample.createCriteria().andEqualTo("orderNumber", orderNumber);
            OrderInfoEntity orderInfoEntity = orderInfoMapper.selectOneByExample(orderInfoExample);

            // 查询所有订单商品数据
            List<OrderProductEntity> orderProductEntities = njkUserMapper.getOrderProducts();

            ArrayList<OrderProductEntity> orderProducts = new ArrayList<>();
            MyOrderModel myOrderModel = new MyOrderModel();
            // 未付款
            if (orderInfoEntity.getOrderStatus().equals("0")) {
                myOrderModel.setOrderStatusName("未付款");
            }
            if (orderInfoEntity.getOrderStatus().equals("1")) {
                myOrderModel.setOrderStatusName("已付款");
            }
            for (OrderProductEntity orderProductEntity : orderProductEntities) {
                // 该订单商品属于该订单
                if (orderInfoEntity.getOrderInfoId().equals(orderProductEntity.getOrderInfoId())) {
                    // 商品规格id
                    String remarkId = orderProductEntity.getRemarkId();
                    ProductRemarkEntity remarkEntity = productRemarkMapper.selectByPrimaryKey(remarkId);
                    if (remarkEntity != null) {
                        orderProductEntity.setPostage(remarkEntity.getPostage());
                        // 总购买数量超过购买数量（说明有赠送的）显示赠送的商品信息
                        if (orderProductEntity.getCountNum() > Integer.valueOf(orderProductEntity.getNumber())) {
                            if (orderProductEntity.getActiveId() == 1) {
                                orderProductEntity.setActiveTypeName(orderProductEntity.getProductName() + ":" + remarkEntity.getRemark() + "  x" + (orderProductEntity.getCountNum() - Integer.valueOf(orderProductEntity.getNumber())));
                            }
                        }

                    }
                    orderProducts.add(orderProductEntity);
                }
            }
            orderInfoEntity.setProductEntities(orderProducts);
            return new ResponseResult(ResponseMessage.OK, orderInfoEntity);
        }

        ArrayList<MyOrderModel> myOrderModels = new ArrayList<>();
        // 我的所有订单
        List<OrderInfoEntity> orderInfoEntities = orderInfoMapper.listMyOrderInfo(userId);
        PageInfo<OrderInfoEntity> orderInfoEntityPageInfo = new PageInfo<>(orderInfoEntities);
        // 得到分页后的订单数据
        List<OrderInfoEntity> orderInfoList = orderInfoEntityPageInfo.getList();

        // 查询所有订单商品数据
        List<OrderProductEntity> orderProductEntities = njkUserMapper.getOrderProducts();
        for (OrderInfoEntity orderInfoEntity : orderInfoList) {
            ArrayList<OrderInfoEntity> orderInfos = new ArrayList<>();
            ArrayList<OrderProductEntity> orderProducts = new ArrayList<>();
            MyOrderModel myOrderModel = new MyOrderModel();
            // 未付款
            if (orderInfoEntity.getOrderStatus().equals("0")) {
                myOrderModel.setOrderStatusName("未付款");
            }
            if (orderInfoEntity.getOrderStatus().equals("1")) {
                myOrderModel.setOrderStatusName("已付款");
            }

            for (OrderProductEntity orderProductEntity : orderProductEntities) {
                // 该订单商品属于该订单
                if (orderInfoEntity.getOrderInfoId().equals(orderProductEntity.getOrderInfoId())) {
                    // 商品规格id
                    String remarkId = orderProductEntity.getRemarkId();
                    ProductRemarkEntity remarkEntity = productRemarkMapper.selectByPrimaryKey(remarkId);
                    if (remarkEntity != null) {
                        orderProductEntity.setPostage(remarkEntity.getPostage());
                        // 总购买数量超过购买数量（说明有赠送的）显示赠送的商品信息
                        if (orderProductEntity.getCountNum() > Integer.valueOf(orderProductEntity.getNumber())) {
                            if (orderProductEntity.getActiveId() == 1) {
                                orderProductEntity.setActiveTypeName(orderProductEntity.getProductName() + ":" + remarkEntity.getRemark() + "  x" + (orderProductEntity.getCountNum() - Integer.valueOf(orderProductEntity.getNumber())));
                            }
                        }

                    }
                    orderProducts.add(orderProductEntity);
                }
            }
            orderInfoEntity.setProductEntities(orderProducts);
            orderInfos.add(orderInfoEntity);
            myOrderModel.setOrderInfoEntities(orderInfos);
            myOrderModels.add(myOrderModel);
        }
        HashMap<String, Object> mm = new HashMap<>();
        mm.put("myOrderModels", myOrderModels);
        mm.put("pages", orderInfoEntityPageInfo.getPages());

        return new ResponseResult(ResponseMessage.OK, mm);
    }

    /**
     * 我的待付款
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult myWaitPay(String userId, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 我的所有待付款订单
        Example orderInfoExample = new Example(OrderInfoEntity.class);
        orderInfoExample.createCriteria().andEqualTo("userId", userId).andEqualTo("orderStatus", "0");
        List<OrderInfoEntity> orderInfoEntities = orderInfoMapper.selectByExample(orderInfoExample);
        PageInfo<OrderInfoEntity> orderInfoEntityPageInfo = new PageInfo<>(orderInfoEntities);
        // 得到分页后的订单数据
        List<OrderInfoEntity> orderInfoList = orderInfoEntityPageInfo.getList();

        ArrayList<MyOrderModel> myOrderModels = new ArrayList<>();

        // 查询所有订单商品数据
        List<OrderProductEntity> orderProductEntities = njkUserMapper.getOrderProducts();
        for (OrderInfoEntity orderInfoEntity : orderInfoList) {
            ArrayList<OrderInfoEntity> orderInfos = new ArrayList<>();
            ArrayList<OrderProductEntity> orderProducts = new ArrayList<>();
            MyOrderModel myOrderModel = new MyOrderModel();
            // 未付款
            myOrderModel.setOrderStatusName("未付款");
            for (OrderProductEntity orderProductEntity : orderProductEntities) {
                // 该订单商品属于该订单
                if (orderInfoEntity.getOrderInfoId().equals(orderProductEntity.getOrderInfoId())) {
                    // 商品规格id
                    String remarkId = orderProductEntity.getRemarkId();
                    ProductRemarkEntity remarkEntity = productRemarkMapper.selectByPrimaryKey(remarkId);
                    if (remarkEntity != null) {
                        orderProductEntity.setPostage(remarkEntity.getPostage());
                        // 总购买数量超过购买数量（说明有赠送的）显示赠送的商品信息
                        if (orderProductEntity.getCountNum() > Integer.valueOf(orderProductEntity.getNumber())) {
                            if (orderProductEntity.getActiveId() == 1) {
                                orderProductEntity.setActiveTypeName(orderProductEntity.getProductName() + ":" + remarkEntity.getRemark() + "  x" + (orderProductEntity.getCountNum() - Integer.valueOf(orderProductEntity.getNumber())));
                            }
                        }
                    }
                    orderProducts.add(orderProductEntity);
                }
            }
            orderInfoEntity.setProductEntities(orderProducts);
            orderInfos.add(orderInfoEntity);
            myOrderModel.setOrderInfoEntities(orderInfos);
            myOrderModels.add(myOrderModel);
        }
        HashMap<String, Object> mm = new HashMap<>();
        mm.put("myOrderModels", myOrderModels);
        mm.put("pages", orderInfoEntityPageInfo.getPages());
        return new ResponseResult(ResponseMessage.OK, mm);
    }

    /**
     * 删除待支付订单
     *
     * @param orderInfoId
     * @return
     * @throws Exception
     */
    public ResponseResult delWaitPay(String orderInfoId, String userId) throws Exception {
        if (orderInfoId != null && !("").equals(orderInfoId)) {
            // 删除单个订单
            orderInfoMapper.deleteByPrimaryKey(orderInfoId);
            // 删除订单下的商品
            Example orderProductExample = new Example(OrderProductEntity.class);
            orderProductExample.createCriteria().andEqualTo("orderInfoId", orderInfoId);
            orderProductMapper.deleteByExample(orderProductExample);
        }

        if (userId != null && !("").equals(userId)) {
            // 查询用户未支付订单
            Example orderInfoExample = new Example(OrderInfoEntity.class);
            orderInfoExample.createCriteria().andEqualTo("userId", userId).andEqualTo("orderStatus", "0");
            List<OrderInfoEntity> orderInfoEntities = orderInfoMapper.selectByExample(orderInfoExample);
            // 删除未支付订单下的商品
            for (OrderInfoEntity orderInfoEntity : orderInfoEntities) {
                Example orderProductExample = new Example(OrderProductEntity.class);
                orderProductExample.createCriteria().andEqualTo("orderInfoId", orderInfoEntity.getOrderInfoId());
                orderProductMapper.deleteByExample(orderProductExample);
            }
            // 清空用户未支付订单
            orderInfoMapper.deleteByExample(orderInfoExample);
        }
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 我的积分明细
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    public ResponseResult myIntegralDetail(String userId, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        Example countCommunityExample = new Example(CountCommunityEntity.class);
        countCommunityExample.createCriteria().andEqualTo("userId", userId);
        List<CountCommunityEntity> countCommunityEntities = countCommunityMapper.selectByExample(countCommunityExample);
        PageInfo<CountCommunityEntity> countCommunityEntityPageInfo = new PageInfo<>(countCommunityEntities);
        return new ResponseResult(ResponseMessage.OK, countCommunityEntityPageInfo);
    }

    /**
     * 我的客服
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public ResponseResult myService(String userId) throws Exception {
        // 查询用户service_id
        NjkUserEntity userEntity = njkUserMapper.selectByPrimaryKey(userId);
        if (userEntity != null) {
            String serviceId = userEntity.getServiceId();
            // 查询客服信息
            NjkUserServiceEntity njkUserServiceEntity = njkUserServiceMapper.selectByPrimaryKey(serviceId);
            return new ResponseResult(ResponseMessage.OK, njkUserServiceEntity);
        }
        return new ResponseResult(ResponseMessage.FAIL, "该用户不存在");
    }

    /**
     * 用户修改密码
     *
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @return
     * @throws Exception
     */
    public ResponseResult updatePassword(String userId, String oldPassword, String newPassword) throws Exception {
        // 查询用户信息
        NjkUserEntity userEntity = njkUserMapper.selectByPrimaryKey(userId);
        if (userEntity == null) {
            return new ResponseResult(ResponseMessage.FAIL, "该用户不存在");
        }
        // 得到加密盐
        String salt = userEntity.getSalt();
        // 对旧密码加密
        String md5Password = MD5.md5(MD5.md5(oldPassword) + salt);
        if (!md5Password.equals(userEntity.getPassword())) {
            return new ResponseResult(ResponseMessage.FAIL, "密码输入不正确");
        }
        // 对新密码加密
        String newMd5Password = MD5.md5(MD5.md5(newPassword) + salt);
        // 修改密码
        userEntity.setPassword(newMd5Password);
        njkUserMapper.updateByPrimaryKeySelective(userEntity);
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 用户充值余额,保存订单
     *
     * @param orderInfoEntity
     * @return
     * @throws Exception
     */
    public ResponseResult rechargeBalance(OrderInfoEntity orderInfoEntity) throws Exception {
        BalanceOrderEntity balanceOrderEntity = new BalanceOrderEntity();
        int i = 0;
        String userId = orderInfoEntity.getUserId();
        // 用户信息
        NjkUserEntity userEntity = njkUserMapper.selectByPrimaryKey(userId);
        Date now = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String s = String.valueOf((int) ((Math.random() * 9 + 1) * 100));
        String orderNumber = s + sdf1.format(now).substring(2); // 订单号
        balanceOrderEntity.setOrderName("余额充值");
        balanceOrderEntity.setOrderNumber(orderNumber);
        balanceOrderEntity.setOrderMoney(orderInfoEntity.getRealityMoney());
        balanceOrderEntity.setPayMethod(orderInfoEntity.getPayMethod());
        balanceOrderEntity.setUserId(userId);
        balanceOrderEntity.setCreateTime(new Date());
        balanceOrderEntity.setUserBalance(userEntity.getBalance() + balanceOrderEntity.getOrderMoney());
        balanceOrderEntity.setOrderStatus(0);
        balanceOrderEntity.setBalanceStatus(1);
        i += balanceOrderMapper.insertSelective(balanceOrderEntity);

        // 保存到orderInfo中
        String orderInfoId = IdUtil.simpleUUID();
        String orderDate = cn.hutool.core.date.DateUtil.now();
        Example userAddressExample = new Example(NjkUserAddressEntity.class);
        userAddressExample.createCriteria().andEqualTo("userId", userId).andEqualTo("defaultAddress", "1");
        // 查询用户地址信息
        NjkUserAddressEntity njkUserAddressEntity = userAddressMapper.selectOneByExample(userAddressExample);
        if (njkUserAddressEntity != null) {
            String userAddress = njkUserAddressEntity.getAddressDetail();
            String userPhone = njkUserAddressEntity.getPhone();
            String userName = njkUserAddressEntity.getName();
            String province = njkUserAddressEntity.getProvince();
            String city = njkUserAddressEntity.getCity();
            orderInfoEntity.setUserAddress(userAddress);
            orderInfoEntity.setUserPhone(userPhone);
            orderInfoEntity.setUserName(userName);
            orderInfoEntity.setProvince(province);
            orderInfoEntity.setCity(city);
        }

        int month = cn.hutool.core.date.DateUtil.month(new Date());
        int year = cn.hutool.core.date.DateUtil.year(new Date());
        String day = cn.hutool.core.date.DateUtil.today();

        orderInfoEntity.setOrderInfoId(orderInfoId);
        orderInfoEntity.setOrderNumber(orderNumber);
        orderInfoEntity.setOrderDate(orderDate);

        orderInfoEntity.setUserId(userId);

        orderInfoEntity.setMonth(month + "");
        orderInfoEntity.setYear(year + "");
        orderInfoEntity.setDay(day);

        i += orderInfoMapper.insertSelective(orderInfoEntity);
        if (i > 0)
            return new ResponseResult(ResponseMessage.OK, balanceOrderEntity);
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 账单明细
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public ResponseResult billDetail(String userId, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        ArrayList<BalanceOrderEntity> balanceOrderEntities = new ArrayList<>();

        if (userId == null)
            return new ResponseResult(ResponseMessage.NULL_REQUEST);
        // 用户已支付的订单
        Example orderInfoExample = new Example(OrderInfoEntity.class);
        orderInfoExample.createCriteria().andEqualTo("userId", userId).andEqualTo("orderStatus", "1");
        List<OrderInfoEntity> orderInfoEntities = orderInfoMapper.selectByExample(orderInfoExample);

        // 该订单下的商品
        for (OrderInfoEntity orderInfoEntity : orderInfoEntities) {
            // 拼接商品名称
            StringBuffer orderName = new StringBuffer();
            orderName.append("购买 ");
            BalanceOrderEntity balanceOrderEntity = new BalanceOrderEntity();

            String orderInfoId = orderInfoEntity.getOrderInfoId();
            Example orderProductExample = new Example(OrderProductEntity.class);
            orderProductExample.createCriteria().andEqualTo("orderInfoId", orderInfoId);
            List<OrderProductEntity> orderProductEntities = orderProductMapper.selectByExample(orderProductExample);
            for (OrderProductEntity orderProductEntity : orderProductEntities) {
                orderName.append(orderProductEntity.getProductName());
            }
            balanceOrderEntity.setOrderName(orderName.toString());
            balanceOrderEntity.setOrderNumber(orderInfoEntity.getOrderNumber());
            balanceOrderEntity.setOrderMoney(orderInfoEntity.getRealityMoney());
            DateTime parse = cn.hutool.core.date.DateUtil.parse(orderInfoEntity.getOrderDate(), "yyyy-MM-dd HH:mm:ss");
            balanceOrderEntity.setCreateTime(parse);
            balanceOrderEntity.setPayMethod(orderInfoEntity.getPayMethod());
            balanceOrderEntity.setUserId(userId);
            balanceOrderEntities.add(balanceOrderEntity);
        }

        // 充值的余额明细
        Example balanceOrderExample = new Example(BalanceOrderEntity.class);
        balanceOrderExample.createCriteria().andEqualTo("balanceStatus", 1).andEqualTo("userId", userId).andEqualTo("orderStatus", 1);
        List<BalanceOrderEntity> balanceOrderEntities1 = balanceOrderMapper.selectByExample(balanceOrderExample);
        balanceOrderEntities.addAll(balanceOrderEntities1);

        // 对结果集按照时间排序
        Collections.sort(balanceOrderEntities, new Comparator<BalanceOrderEntity>() {
            @Override
            public int compare(BalanceOrderEntity b1, BalanceOrderEntity b2) {
                return b1.getCreateTime().compareTo(b2.getCreateTime());
            }
        });
        // 反转集合降序排
        Collections.reverse(balanceOrderEntities);
        // 对结果进行分页
        PageInfo<BalanceOrderEntity> balanceOrderEntityPageInfo = new PageInfo<>(balanceOrderEntities);
        return new ResponseResult(ResponseMessage.OK, balanceOrderEntityPageInfo);
    }

    /**
     * 余额明细
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public ResponseResult balanceDetail(String userId, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        Example balanceOrderExample = new Example(BalanceOrderEntity.class);
        balanceOrderExample.createCriteria().andEqualTo("userId", userId).andEqualTo("orderStatus", 1);
        List<BalanceOrderEntity> balanceOrderEntities = balanceOrderMapper.selectByExample(balanceOrderExample);
        PageInfo<BalanceOrderEntity> balanceOrderEntityPageInfo = new PageInfo<>(balanceOrderEntities);
        return new ResponseResult(ResponseMessage.OK, balanceOrderEntityPageInfo);
    }

    /**
     * 插入个推识别用户id——clientId
     *
     * @param clientId
     * @return
     * @throws Exception
     */
    public ResponseResult insertClientId(String userId,String clientId) throws Exception {
        NjkUserEntity user = njkUserMapper.selectByPrimaryKey(userId);
        if(user.getClientId() == null || ("").equals(user.getClientId())){
            // 向该用户中插入clientId
            NjkUserEntity userEntity = new NjkUserEntity();
            userEntity.setUserId(userId);
            userEntity.setClientId(clientId);
            int i = njkUserMapper.updateByPrimaryKeySelective(userEntity);
            if(i > 0)
                return new ResponseResult(ResponseMessage.OK);
            return new ResponseResult(ResponseMessage.FAIL);
        }
        return new ResponseResult(ResponseMessage.OK);
    }

    /**
     * 每日凌晨清除用户定时连续签到信息
     */
    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional
    public void userDaySign() {
        // 查询用户签到表
        List<UserSignEntity> userSignEntities = userSignMapper.selectAll();
        for (UserSignEntity userSignEntity : userSignEntities) {
            if (userSignEntity.getToday() == 0) {
                userSignEntity.setDaysNum(0);
            }
            if (userSignEntity.getToday() == 1) {
                userSignEntity.setToday(0);
            }
            userSignMapper.updateByPrimaryKeySelective(userSignEntity);
        }
    }

}